// 导入导出弹层

import { ElButton, ElDialog, ElInput } from "element-plus";
import { createVNode, defineComponent, reactive, render } from "vue";

const DialogComponent = defineComponent({
  props: {
    option: { type: Object },
  },
  setup(props, ctx) {
    const state = reactive({
      option: props.option, // 用户传入的属性
      isShow: false, // 用于弹层的显示隐藏
    });

    // 暴露方法
    ctx.expose({
      showDialog(option) {
        state.option = option;
        state.isShow = true;
      },
    });

    // 取消
    const onCancel = () => {
      state.isShow = false; // 弹层隐藏
    };
    // 确定
    const onConfirm = () => {
      state.isShow = false;
      // 其它操作
      state.option.onConfirm && state.option.onConfirm(state.option.content);
    };

    return () => {
      return (
        <ElDialog v-model={state.isShow} title={state.option.title}>
          {{
            default: () => <ElInput type="textarea" v-model={state.option.content} rows="10"></ElInput>,
            footer: () =>
              state.option.footer && (
                <div>
                  <ElButton onClick={onCancel}>取消</ElButton>
                  <ElButton type="primary" onClick={onConfirm}>
                    确定
                  </ElButton>
                </div>
              ),
          }}
        </ElDialog>
      );
    };
  },
});

let vm;
export function $dialog(option) {
  // 手动挂载组件  $mount()
  if (!vm) {
    let el = document.createElement("div");
    vm = createVNode(DialogComponent, { option }); // 将组件渲染成虚拟节点
    document.body.appendChild((render(vm, el), el));
  }
  // 将组件渲染到el上  调用组件暴露的方法
  let { showDialog } = vm.component.exposed;
  showDialog(option);
}
